package FenxiaoOrderService

import (
	toolsDb "gdshop-back-end-go/common/db"
	"gdshop-back-end-go/common/request/BaseReq"
	"gdshop-back-end-go/common/response"
	"gdshop-back-end-go/common/tools"
	"gdshop-back-end-go/service-order/OrderService"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gconv"
)

func Page(r *ghttp.Request, req *BaseReq.I) *response.JsonResponse {
	ctx := r.GetCtx()
	obj := toolsDb.GetUnSafaTable(ctx, "order").As("o").LeftJoin("member m", "m.id = o.member_id").
		LeftJoin("order_price op", "o.id = op.order_id").LeftJoin("store s", "o.store_id = s.id").
		Order("o.id DESC")
	countObj := toolsDb.GetUnSafaTable(ctx, "order").As("o").LeftJoin("member m", "m.id = o.member_id").
		LeftJoin("order_price op", "o.id = op.order_id").LeftJoin("store s", "o.store_id = s.id")
	SelectFields := g.ArrayStr{
		"o.*",
		"m.realname AS buy_realname",
		"m.mobile AS buy_mobile",
		"op.dispatch_price_change",
		"op.total_price_change",
		"s.store_name",
	}

	listTypeWhere := ""
	listType := r.GetInt("list_type", 0)
	if listType > 0 {
		listTypeWhere = " AND status = " + gconv.String(listType)
	}

	obj.Where("o.delete_at<1")
	obj.Where("o.id IN (SELECT fo.order_id FROM gd_fenxiao_order fo WHERE fo.delete_at<1 AND fo.handle_status=1" + listTypeWhere + ")")
	countObj.Where("o.delete_at<1")
	countObj.Where("o.id IN (SELECT fo.order_id FROM gd_fenxiao_order fo WHERE fo.delete_at<1 AND fo.handle_status=1" + listTypeWhere + ")")

	countObj.Fields("1")
	obj.Fields(SelectFields)

	count, err := countObj.Count()
	if err != nil {
		return response.FailByRequestMessage(r, err.Error())
	}

	res, err := obj.Page(req.Page, req.PageSize).All()
	if err != nil {
		return response.FailByRequestMessage(r, err.Error())
	}

	resList := res.List()
	var orderIds []int
	for _, item := range resList {
		orderIds = append(orderIds, gconv.Int(item["id"]))
	}
	subList := OrderService.GetOrderSubAndFenxiaoListByOrderIds(ctx, orderIds)
	for _, item := range resList {
		orderId := gconv.Int(item["id"])
		item["subs"] = subList[orderId]
		if len(gconv.String(item["store_name"])) < 1 {
			item["store_name"] = "自营"
		}
	}

	return response.SuccessByRequestMessageData(nil, "获取成功",
		g.Map{
			"list":       resList,
			"pagination": tools.GetPageInfo(count, req.Page, req.PageSize),
		})
}
